package com.qadev.appergodic.utils;

import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.*;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by wjp on 2019/8/7.
 */
public class AutoScreen {
    IOUtils ioUtils =new IOUtils();
    BufferedImageBuilderUtils bufferedImageBuilderUtils =new BufferedImageBuilderUtils();
    /**
     * 点击元素后并截图保存
     * @param driver 安卓驱动
     * @param path 图片路径
     * @param xpath 点击的元素
     */
    public  void autoSceenAndroid(AndroidDriver driver, String path, String xpath){
        try {
            //判断元素是否存在
            boolean flag = false;
            //将点击的元素封装起来
            WebElement element =driver.findElement(By.xpath(xpath));
            //元素位置
            Point point=element.getLocation();
            System.out.println("横坐标为："+point.getX()+"纵坐标为："+point.getY());
            //元素大小
            Dimension dimension= element.getSize();
            //标记元素位置
            System.out.println("长度为："+dimension.getWidth()+"宽度为："+dimension.getHeight());
            if (null!=element) {
                // TODO: 2019/8/6 将点击的元素位置标记
                //单击后sleep两秒，开始截图保存
                Thread.sleep(2000);
                String activityname = driver.currentActivity();
                File Screen = driver.getScreenshotAs(OutputType.FILE);
                BufferedImage image=drawDesigns(Screen,dimension,point);
                String screenname = String.valueOf(System.currentTimeMillis());
                ImageIO.write(image, "jpeg", new File(path + activityname+screenname + ".jpg"));
//                FileUtils.copyFile(Screen, new File(path + screenname + ".jpg"));
                element.click();
                //返回上一级页面
            }
        } catch (Exception e) {
            System.out.println("测试元素没有获取");
            e.printStackTrace();
        }

    }

    /**
     *  截图并没有标记
     * @param driver
     * @param path
     */
    public  void autoSceenAndroid(AndroidDriver driver, String path,Dimension dimension,Point point,String activityname){
        try {
            //判断元素是否存在
            boolean flag = false;
            //将点击的元素封装起来
            // TODO: 2019/8/6 将点击的元素位置标记
            File Screen = driver.getScreenshotAs(OutputType.FILE);
            //单击后sleep两秒，开始截图保存
            Thread.sleep(2000);
            //获取系统时间
            String screenname = String.valueOf(System.currentTimeMillis());
            BufferedImage image=drawDesigns(Screen,dimension,point);
            ImageIO.write(image, "jpeg", new File(path + activityname+screenname + ".jpg"));        }
            catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * synchronized截图 确保driver不会偏移
     * @param driver
     * @param path
     * @param element
     * @param activityname
     * @return true截图成功 false截图失败
     */
    public  boolean autoSceenAndroid(AndroidDriver driver, String path,MobileElement element,String activityname){
        boolean flag = false;
        try {
            if(element==null){
                return flag;
            }
            //判断元素是否存在
            //将点击的元素封装起来
            // TODO: 2019/8/6 将点击的元素位置标记
            File Screen = driver.getScreenshotAs(OutputType.FILE);
            //单击后sleep两秒，开始截图保存
//            Thread.sleep(2000);
            //获取系统时间
            String screenname = String.valueOf(System.currentTimeMillis());
            BufferedImage image=drawDesigns(Screen,getDimension(element),getPoint(element));
            ImageIO.write(image, "jpeg", new File(path + activityname+screenname + ".jpg"));
            flag=true;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    //高亮显示元素
    public void highlightElement(AndroidDriver driver,WebElement element) {
        String js = "arguments[0].style.border='6px solid red'";
        JavascriptExecutor executor=(JavascriptExecutor) driver;
        executor.executeScript(js,element);

    }

    /**
     * 获取元素列表
     * @param driver
     * @param xpath
     */
    public List<MobileElement> listElements(AndroidDriver driver, String xpath) {
        List<MobileElement> listelements =null;
        try {
            System.out.println("xpath："+xpath);
            listelements =driver.findElements(By.xpath(xpath));
        }catch (Exception e){
            e.printStackTrace();
        }
        return listelements;

    }

    /**
     * 获取元素表表并做点击操作
     * @param driver
     * @param xpath
     * @param filepath
     * @return
     */
    public List<MobileElement> listElements(AndroidDriver driver, String xpath,String filepath,String activityname) {
        List<MobileElement> listelements =null;
        try {
            listelements =driver.findElements(By.xpath(xpath));
            for (WebElement element: listelements
                 ) {

                String acname=driver.currentActivity();
                //标记元素并截图
                autoSceenAndroid(driver,filepath,element.getSize(),element.getLocation(),acname);
                System.out.println("元素名字"+element.toString());
                element.click();
                //获取页面pagesource并保存为xml文件
                avToXml(filepath,driver);
                // TODO: 2019/8/7 返回上一个页面
                Runtime.getRuntime().exec("adb shell input keyevent 4");
                //可能页面已经不存在对应元素需要重新获取页面元素

            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return listelements;

    }
    /**
     * 操作截图并标记元素类似高亮
     *@param picture 图片流文件
     *@param dimension 元素大小
     *@param point 元素位置
     */
    public BufferedImage drawDesigns(File picture,Dimension dimension,Point point) throws IOException{
            //当做字节流处理
         Image src=Toolkit.getDefaultToolkit().getImage(picture.getPath());
         BufferedImage image=bufferedImageBuilderUtils.toBufferedImage(src);
//       BufferedImage image = ImageIO.read(picture); 读取图片引起ICC问题，在图片上会有一层红色蒙层，用转换字节流的方式解决
         Graphics2D g = (Graphics2D) image.getGraphics();
         g.setColor(Color.RED);//画笔颜色
         g.drawRect(point.getX()-1,point.getY(),dimension.getWidth()+2,dimension.getHeight()+2);//矩形框(原点x坐标，原点y坐标，矩形的长，矩形的宽)
         g.dispose();
         return image;
    }
    /** 暂时用adb执行，其他再找实现方法
     todo:返回上一个页面
     1、页面跳转有返回或者滑动
     2、页面跳转到时没有返回按钮的情况
     */
    public void skipOldpage(AndroidDriver driver){
        try {
            Thread.sleep(3000);
            driver.navigate().back();

//            Runtime.getRuntime().exec("adb shell input keyevent 4");
            Thread.sleep(3000);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取元素坐标 point
     */
    public Point getPoint(MobileElement element){
        Point point =element.getLocation();
        return point;
    }
    /**
     * 获取U元素大小Dimension
     */
    public Dimension getDimension(MobileElement element) throws BusinessException {
        Dimension dimension =element.getSize();
        return dimension;
    }
    /**
     * 获取页面PageSource生成xml
     *
     */
    public void avToXml(String filepath, AndroidDriver driver){
        String strPageSource= driver.getPageSource();
        String strAvtivityName=driver.currentActivity();
        String lo = String.valueOf(System.currentTimeMillis());
        ioUtils.strChangeWord(filepath+strAvtivityName+lo+".xml",strPageSource);
    }
    /**
     * 可能页面已经不存在对应元素需要重新获取页面元素两个步骤
     * 1、判断页面的activityname时候修改，如果修改直接返回false
     * 2、如果也没按的activname没有变换，判断页面时候有该元素
     */
    public boolean existElement(AndroidDriver driver,MobileElement element){
        boolean exist=true;
        driver.findElement(By.id("1"));




        return exist;
    }
    /** todo
     * 跳转的页面包含webview时处理
     */
    public void changePage(AndroidDriver driver){
        String activation="";
        Set set=new HashSet();
        set.addAll(driver.getContextHandles()); //上下文类型？native_app和WEBVIEW_app package
        Iterator it=set.iterator();
        while (it.hasNext()){
            System.out.println("一个迭代器，我也不知道是很么！"+it.next());
        }
        //切换到native
        driver.context("NATIVE_APP");
        //切换到webview
        driver.context("WEBVIEW_app");
    }
}
